/**
 * 全局变量定义位置
 */
var gArray_DataGrid_Column = new Array();
var gArray_DataGrid_Column_Inti = new Array();

/**
 * 获取url中的参数
 * @param name
 * @returns
 */
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值decodeURI
}
/**
 * 获取JSONObject指定字符串中的参数
 * @param name
 * @returns
 */
function getJSONObjectValueByKey(Arg_Conten, Arg_Key) {
    var reg = new RegExp("(^|,)" + Arg_Key + ":([^,]*)(,|$)"); //构造一个含有目标参数的正则表达式对象
    var r = Arg_Conten.match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}
/**
 * 获取Url指定参数的参数
 * @param name
 * @returns
 */
function getUrlParamValueByKey(Arg_Conten, Arg_Key) {
	var reg = new RegExp("(^|&)" + Arg_Key + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = Arg_Conten.match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}
/**
 * 获取url中的全部参数
 * @returns
 */
function getUrlFullParam() {
	var ls_Url = window.location.href;
	var li_StrStart = ls_Url.indexOf("?");
	var ls_FullParam = ls_Url.substr(li_StrStart + 1);
	
    if (ls_FullParam != null) return ls_FullParam; return null; //返回参数值
}
/**
 * 获取url中的全部参数
 * @returns
 */
function getUrlFullParam(Arg_URL) {
	var li_StrStart = Arg_URL.indexOf("?");
	var ls_FullParam = Arg_URL.substr(li_StrStart + 1);
	
    if (ls_FullParam != null) return ls_FullParam; return null; //返回参数值
}
/**
 * 获取日期
 * @param strDate
 * @returns
 */
function getDate(strDate) {    
    var date = eval('new Date(' + strDate.replace(/\d+(?=-[^-]+$)/,    
    function (a) { return parseInt(a, 10) - 1; }).match(/\d+/g) + ')');    
    return date;    
}
/**
 * 根据条件加载入库企业列表
 */
function Load_Enterprise(Arg_ControlName, Arg_Condition){
	$("#" + Arg_ControlName).combobox({
		url:'Search_Enterprise.action',
		required:true,
		queryParams:{Where: Arg_Condition},
		valueField:'EnterpriseID',
		textField:'Enterprise',
		editable:true,
		fit:true
		//onChange:Combobox_onChange_Enterprise
	});
	
}
/**
 * 对话框属性设置
 */
function Set_Dialog_Attribute(Arg_ControlName){
	$("#" + Arg_ControlName).dialog({
		buttons: [{
			text:'确定',
			iconCls:'icon-ok',
			handler:selectMaterial
		},{
			text:'关闭',
			iconCls:'icon-cancel',
			handler:dialogClose
		}]
	});
}
/**
 * 关闭物料选择对话框
 */
function dialogClose(){
	$('#dlg').dialog('close');
}
/**
 * 加载物料
 */
function dialogOpen(){	
	if (endEditing()){
		$('#dlg').dialog('open');
		loadMaterial()
	}
}/**
 * 根据条件加载购销订单列表
 */
function Load_PO_ID(Arg_ControlName, Arg_Condition){
	$("#" + Arg_ControlName).combobox({
		url:'Select_PO.action',
		required:true,
		queryParams:{Where: Arg_Condition},
		valueField:'PO_ID',
		textField:'PO_ID',
		editable:false,
		fit:true
		//onChange:Combobox_onChange_Enterprise
	});
}
/**
 * 加载购销订单combogrid
 */
function Load_PO(Arg_ControlName, Arg_Condition){
	$('#' + Arg_ControlName).combogrid({
		panelWidth: 680,
		url:'Select_PO.action',
		queryParams:{Where:Arg_Condition},
		idField:'PO_ID',
		textField:'Contract_ID_Party',
		columns: [[
					{field:'PO_ID', title:'采购订单号', width:80,hidden:false},
					{field:'Enterprise', title:'卖方'},
					{field:'Downstream_Enterprise', title:'买方'},
					{field:'Contract_ID_Party', title:'卖方合同号'},
					{field:'Contract_ID_Other_Party', title:'买方合同号'},
				]],
		fitColumns: true,
		required: true,
		editable: false,
		onChange: ComboGrid_onChange_PO
	});
}
/**
 * 加载购销订单不带事件combogrid
 */
function Load_POWithoutEvent(Arg_ControlName, Arg_Condition){
	$('#' + Arg_ControlName).combogrid({
		panelWidth: 680,
		url:'Select_PO.action',
		queryParams:{Where:Arg_Condition},
		idField:'PO_ID',
		textField:'Contract_ID_Party',
		columns: [[
					{field:'PO_ID', title:'采购订单号', width:80,hidden:false},
					{field:'Enterprise', title:'卖方'},
					{field:'Downstream_Enterprise', title:'买方'},
					{field:'Contract_ID_Party', title:'卖方合同号'},
					{field:'Contract_ID_Other_Party', title:'买方合同号'},
				]],
		fitColumns: true,
		required: true,
		editable: false,
		//onChange: ComboGrid_onChange_PO
	});
}
/**
 * 通用格式化日期时间类型为日期类型
 * @param val
 * @param row
 * @param index
 * @returns
 */
function Format_Date(val, row, index) {
	if (val != undefined){
		var ls_DateTime = val.split(" ");
		return ls_DateTime[0]
	}
	
}
/**
 * 通用格式化数字为小数点两位
 * @param val
 * @param row
 * @param index
 * @returns
 */
function Format_Number(val, row, index) {
	if (val != undefined) {
		var lArray_Number = parseFloat(val).toFixed(2).split(".");
		
		return toThousands(lArray_Number[0]) + "." +lArray_Number[1]
	}
}
/**
 * 将字符加上千分符
 * @param num
 * @returns
 */
function toThousands(num) {
    return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
}
/**
 * 格式化百分数
 * @param num
 * @returns
 */
function changeToPercent(num) {
	 if(!/\d+\.?\d+/.test(num) && num != "0") {
		 alert("必须为数字");
	 }
	 var result = (num * 100).toString(),
	 index = result.indexOf(".");
	 if(index == -1 || result.substr(index+1).length <= 4) {
		 return result + "%";
	 }
	 return result.substr(0, index + 5) + "%";
}
/**
 * 发送Email
 * @returns
 */
function sendEmail(Arg_Email, Arg_Context){
	 $("#send").attr("href","mailto:" + Arg_Email + "?body=" + Arg_Context);
	 document.getElementById("send").click();
}
/**
 * 阿拉伯数字转中文大写
 * @param Num
 * @returns
 */
function Arabia_to_Chinese(Num) {
	for(i=Num.length-1;i>=0;i--) {
		 Num = Num.replace(",","")//替换tomoney()中的“,”
		 Num = Num.replace(" ","")//替换tomoney()中的空格
	}
	Num = Num.replace("￥","")//替换掉可能出现的￥字符
	if(isNaN(Num)) { //验证输入的字符是否为数字
		alert("请检查小写金额是否正确");
		return;
	}
	//字符处理完毕后开始转换，采用前后两部分分别转换
	part = String(Num).split(".");
	newchar = ""; 
	//小数点前进行转化
	for(i=part[0].length-1;i>=0;i--) {
		if(part[0].length > 10) {
			alert("位数过大，无法计算");
			return "";
		}//若数量超过拾亿单位，提示
		tmpnewchar = ""
		perchar = part[0].charAt(i);
		switch (perchar) {
			case "0": tmpnewchar="零" + tmpnewchar ;break;
			case "1": tmpnewchar="壹" + tmpnewchar ;break;
			case "2": tmpnewchar="贰" + tmpnewchar ;break;
			case "3": tmpnewchar="叁" + tmpnewchar ;break;
			case "4": tmpnewchar="肆" + tmpnewchar ;break;
			case "5": tmpnewchar="伍" + tmpnewchar ;break;
			case "6": tmpnewchar="陆" + tmpnewchar ;break;
			case "7": tmpnewchar="柒" + tmpnewchar ;break;
			case "8": tmpnewchar="捌" + tmpnewchar ;break;
			case "9": tmpnewchar="玖" + tmpnewchar ;break;
		}
		switch (part[0].length-i-1) {
			case 0: tmpnewchar = tmpnewchar +"元" ;break;
			case 1: if(perchar!=0)tmpnewchar= tmpnewchar +"拾" ;break;
			case 2: if(perchar!=0)tmpnewchar= tmpnewchar +"佰" ;break;
			case 3: if(perchar!=0)tmpnewchar= tmpnewchar +"仟" ;break;
			case 4: tmpnewchar= tmpnewchar +"万" ;break;
			case 5: if(perchar!=0)tmpnewchar= tmpnewchar +"拾" ;break;
			case 6: if(perchar!=0)tmpnewchar= tmpnewchar +"佰" ;break;
			case 7: if(perchar!=0)tmpnewchar= tmpnewchar +"仟" ;break;
			case 8: tmpnewchar= tmpnewchar +"亿" ;break;
			case 9: tmpnewchar= tmpnewchar +"拾" ;break;
		}
		newchar = tmpnewchar + newchar;
	}
	//小数点之后进行转化
	if(Num.indexOf(".")!=-1) {
		if(part[1].length > 2) {
			alert("小数点之后只能保留两位,系统将自动截断");
			part[1] = part[1].substr(0,2)
		}
		for(i=0;i<part[1].length;i++) {
			tmpnewchar = ""
			perchar = part[1].charAt(i)
			switch(perchar) {
				case "0": tmpnewchar="零" + tmpnewchar ;break;
			    case "1": tmpnewchar="壹" + tmpnewchar ;break;
			    case "2": tmpnewchar="贰" + tmpnewchar ;break;
			    case "3": tmpnewchar="叁" + tmpnewchar ;break;
			    case "4": tmpnewchar="肆" + tmpnewchar ;break;
			    case "5": tmpnewchar="伍" + tmpnewchar ;break;
			    case "6": tmpnewchar="陆" + tmpnewchar ;break;
			    case "7": tmpnewchar="柒" + tmpnewchar ;break;
			    case "8": tmpnewchar="捌" + tmpnewchar ;break;
			    case "9": tmpnewchar="玖" + tmpnewchar ;break;	
			}
			if(i==0)tmpnewchar =tmpnewchar + "角";
			if(i==1)tmpnewchar = tmpnewchar + "分";
			newchar = newchar + tmpnewchar;
		}
	}
	//替换所有无用汉字
	while(newchar.search("零零") != -1)
		newchar = newchar.replace("零零", "零");
		newchar = newchar.replace("零亿", "亿");
		newchar = newchar.replace("亿万", "亿");
		newchar = newchar.replace("零万", "万");
		newchar = newchar.replace("零元", "元");
		newchar = newchar.replace("零角", "");
		newchar = newchar.replace("零分", "");
		if (newchar.charAt(newchar.length-1) == "元" || newchar.charAt(newchar.length-1) == "角")
			newchar = newchar+"整"
	return newchar;
}
/**
 * 定义datagrid列标题
 * @param Arg_Element_ID datagrid的id号
 * @param Arg_Scene 使用的场景 Add：新增；Add_Inti：新增初始；Modify：查询、修改、删除
 * @param Arg_JSONArray 要处理的JSONArray
 * @returns
 */
function Defined_Datagrid_Column_Title(Arg_Element_ID, Arg_Scene, Arg_JSONArray) {
	var lDataGrid_Opts;
	var lDatagrid_ID;
	if (this == Arg_Element_ID) {
		lDatagrid_ID = Arg_Element_ID.id;
		//lDataGrid_Opts = $(Arg_Element_ID).edatagrid("options");
	} else {
		lDatagrid_ID = Arg_Element_ID;
	}
	lDataGrid_Opts = $("#" + lDatagrid_ID).edatagrid("options");
	var lJSONArray_Columns_Opts = lDataGrid_Opts.columns[0];
	var lJSONObject_Column_Opts_Inti = {field:'Size_Class', title:'', editor:{type:'textbox', options:{editable:false}}, fixed:true, width:100};
	var lJSONObject_Column_Size_Opts_Inti = {field:'', title:'', editor:{type:'numberbox', options:{editable:false}}, fixed:true, width:60};
	/**
	 * Arg_JSONArray中需要的数据
	 * 1.要知道最长Size_Class的长度
	 * 2.当前要加载的Size_Class列表
	 * 形式如下：
	 * {Size_Class_Longest_Length:数值,Size_Class:{666:[{},{},{}],男鞋UK:[{},{},{}]}}
	 * 加载列标题的步骤
	 * 1.先检查是否为第一次加载尺码套系
	 * 2.如果是在下标为零的数组中加入列
	 * 3.如果不是在下表为N的数据中加入列
	 */
	var li_Size_Class_Longest_Length = Arg_JSONArray.Size_Class_Longest_Length;
	var li_Columns_Opts_Counter = 0;
	var li_Counter = 0;
	var lJSONArray_Add_Columns_Opts = new Array();
	
	$.map(Arg_JSONArray.Size_Class, function(Size_Class, Size_Class_Name){
		
		var ls_Datagrid_Opts = JSON.stringify(lDataGrid_Opts);
		if (ls_Datagrid_Opts.indexOf(Size_Class_Name) < 0) {
			//没有此列头
			li_Counter = 0;
			var lJSONObject_Column_Opts_New = $.parseJSON(JSON.stringify(lJSONObject_Column_Opts_Inti));
			lJSONObject_Column_Opts_New.title = Size_Class_Name;
			lJSONArray_Add_Columns_Opts[li_Columns_Opts_Counter] = new Array();
			lJSONArray_Add_Columns_Opts[li_Columns_Opts_Counter][li_Counter] = lJSONObject_Column_Opts_New;
			$.map(Size_Class, function(Column, Index) {
				if (Column !== undefined) {
					//li_Counter += 1;
					var lJSONObject_Column_Size_Opts_New = $.parseJSON(JSON.stringify(lJSONObject_Column_Size_Opts_Inti));
					lJSONObject_Column_Size_Opts_New.field = Column.Size_Postion;
					//alert(Column.Size);
					//if (Column.Size != "") {
					//	lJSONObject_Column_Size_Opts_New.editor.options.editable = true;
					//} else {
					//	lJSONObject_Column_Size_Opts_New.editor.options.editable = false;
					//}
					lJSONObject_Column_Size_Opts_New.title = Column.Size;
					lJSONArray_Add_Columns_Opts[li_Columns_Opts_Counter][Index + 1] = lJSONObject_Column_Size_Opts_New;
				}
			});
		}
		li_Columns_Opts_Counter += 1;
	});
	if (lJSONArray_Add_Columns_Opts.length != 0) {
		if (JSON.stringify(lJSONArray_Columns_Opts).indexOf("Size_Class") > 0) {
			//不是第一次加载尺码套系
			var li_DataGrid_Opts_Columns_Counter = lDataGrid_Opts.columns.length;
			for (li_Counter = 0; li_Counter < lJSONArray_Add_Columns_Opts.length; li_Counter++) {
				lDataGrid_Opts.columns[li_DataGrid_Opts_Columns_Counter] = new Array();
				lDataGrid_Opts.columns[li_DataGrid_Opts_Columns_Counter] = lDataGrid_Opts.columns[li_DataGrid_Opts_Columns_Counter].concat(lJSONArray_Add_Columns_Opts[li_Counter]);
				li_DataGrid_Opts_Columns_Counter += 1;
			}
			$.map(lJSONArray_Columns_Opts, function(Column) {
				if (Column.hasOwnProperty("rowspan")) {
					Column.rowspan += 1;
				}
			})
		} else {
			//检测到这是第一次加载尺码套系
			var li_DataGrid_Opts_Columns_Counter = 0;
			for (li_Counter = 0; li_Counter < lJSONArray_Add_Columns_Opts.length; li_Counter++) {
				if (lDataGrid_Opts.columns[li_DataGrid_Opts_Columns_Counter] === undefined) {
				    // array empty or does not exist
					lDataGrid_Opts.columns[li_DataGrid_Opts_Columns_Counter] = new Array();
					lDataGrid_Opts.columns[li_DataGrid_Opts_Columns_Counter] = lDataGrid_Opts.columns[li_DataGrid_Opts_Columns_Counter].concat(lJSONArray_Add_Columns_Opts[li_Counter]);
				} else {
					lDataGrid_Opts.columns[li_DataGrid_Opts_Columns_Counter] = lDataGrid_Opts.columns[li_DataGrid_Opts_Columns_Counter].concat(lJSONArray_Add_Columns_Opts[li_Counter]);
				}
				li_DataGrid_Opts_Columns_Counter += 1;
			}
			$.map(lJSONArray_Columns_Opts, function(Column) {
				if (Column.hasOwnProperty("rowspan")) {
					Column.rowspan = lJSONArray_Add_Columns_Opts.length;
				}
			})
		};
		$("#" + lDatagrid_ID).edatagrid({columns:lDataGrid_Opts.columns});
	}

	//alert(JSON.stringify(lJSONArray_Columns_Opts).indexOf("Size_Class"));
	//alert(lJSONObject_Column_Opts_Inti.hasOwnProperty("field"));
}
/**
 * 清除指定datagrid列标题
 * @param Arg_Element_ID datagrid的id号
 * @returns
 */
function Clear_Datagrid_Column_Title(Arg_Element_ID) {
	var lDataGrid_Opts = $("#" + Arg_Element_ID).datagrid("options");
	var lJSONArray_Column_Title = lDataGrid_Opts.columns;
	
	
}
/**
 * textbox清除按钮
*/
$.extend($.fn.textbox.methods, {
    addClearBtn: function(jq, iconCls){
        return jq.each(function(){
            var t = $(this);
            var opts = t.textbox('options');
            opts.icons = opts.icons || [];
            if (opts.icons.length == 0) {
                opts.icons.unshift({
                    iconCls: iconCls,
                    handler: function(e){
                        $(e.data.target).textbox('clear').textbox('textbox').focus();
                        $(this).css('visibility','hidden');
                    }
                });
            }

            t.textbox();
        	if (!t.textbox('getText')){
                t.textbox('getIcon',0).css('visibility','hidden');
            }
            t.textbox('textbox').bind('keyup', function(){
                var icon = t.textbox('getIcon',0);
                if ($(this).val()){
                    icon.css('visibility','visible');
                } else {
                    icon.css('visibility','hidden');
                }
            }).bind('mouseup', function(){
                var icon = t.textbox('getIcon',0);
                if ($(this).val()){
                    icon.css('visibility','visible');
                } else {
                    icon.css('visibility','hidden');
                }
            });
        });
    }
});
/**
 * 给指定的datagrid中可以编辑控件添加清除按钮
 * @param Arg_Datagrid
 * @param Arg_Index
 * @returns
 */
function Datagrid_Editor_AddClearBtn(Arg_Datagrid, Arg_Index) {
	var editors;
	if (this == Arg_Datagrid) {
		editors = $(Arg_Datagrid).datagrid('getEditors', Arg_Index)
	} else {
		editors = $("#" + Arg_Datagrid).datagrid('getEditors', Arg_Index)
	}
	var li_Editors = editors.length;
	if (li_Editors > 0) {
		var li_Counter;
		for (li_Counter = 0; li_Counter < li_Editors; li_Counter++) {
			var editor = editors[li_Counter].target;
			if (editors[li_Counter].field != "Size_Class") {
				if ($(editor).hasClass('textbox-f')){
					$(editor).textbox('addClearBtn', 'icon-clear');
				}
			} else {
				$(editor).textbox({icons: []});
			}
		}
	}
}
/**
 * 给指定的Div中元素添加清除按钮
 * @param Arg_Div_ID
 * @returns
 */
function Div_Element_AddClearBtn(Arg_Div_ID) {
	$("#" + Arg_Div_ID).find("div").children(":input").map(function(){
		if ($(this).hasClass('easyui-textbox')){
			$(this).textbox('addClearBtn', 'icon-clear');
		} else if ($(this).hasClass('easyui-combobox')) {
			$(this).combobox().textbox('addClearBtn', 'icon-clear');
		} else if ($(this).hasClass('easyui-datebox')) {
			$(this).datebox().textbox('addClearBtn', 'icon-clear');
		} else if ($(this).hasClass('easyui-numberbox')) {
			$(this).numberbox().textbox('addClearBtn', 'icon-clear');
		}
	})
}
/**
 * 给指定的datagrid中可以编辑控件添加事件
 * @param Arg_Datagrid
 * @param Arg_Index
 * @returns
 */
function Datagrid_Editor_AddEvents(Arg_Datagrid, Arg_Index) {
	var lDatagrid_ID;
	if (this == Arg_Datagrid) {
		lDatagrid_ID = Arg_Datagrid.id;
		//var editors = $(Arg_Datagrid).datagrid('getEditors', Arg_Index);
		//var lJSONObject_CurrentRow = $(Arg_Datagrid).datagrid("getSelected");
	} else {
		lDatagrid_ID = Arg_Datagrid;
	}
	var editors = $("#" + lDatagrid_ID).datagrid('getEditors', Arg_Index);
	//var lJSONObject_CurrentRow = $("#" + lDatagrid_ID).datagrid("getSelected");
	
	var li_Editors = editors.length;
	if (li_Editors > 0) {
		$.map(editors, function(editor) {
			if (editor.field == "Article_Number") {
				$(editor.target).textbox({
					onChange:function(newValue, oldValue) {
						$.ajax({type:'post',      
						    url:'Query_Size_ClassUesd_ByArticleNumberOrPO_Number_Web.action',
							data:{Article_Number_Data:newValue},
						    cache:false,  
						    dataType:'json',  
						    success:function(data) {
						    	var editor = $("#" + lDatagrid_ID).edatagrid('getEditor', {index:Arg_Index, field:"Size_Class"});
						    	if (data.Status == "success") {
						    		Defined_Datagrid_Column_Title(lDatagrid_ID, "Add", data);
									
						    		$.map(data.Size_Class, function(Column, Size_Class) {
						    			//var editor = $("#" + lDatagrid_ID).edatagrid('getEditor', {index:Arg_Index, field:"Size_Class"});
						    			if (editor == null) {
						    				editor = $("#" + lDatagrid_ID).edatagrid('getEditor', {index:Arg_Index, field:"Size_Class"});
						    				//$(editor.target).textbox("setValue", Size_Class);
						    			}
						    			editor = $("#" + lDatagrid_ID).edatagrid('getEditor', {index:Arg_Index, field:"Size_Class"});
						    			$(editor.target).textbox("setValue", Size_Class);
						    			$.map(Column, function(field) {
											if (Valid_Size_Field(field.Size_Postion) && field.Size != "") {
												editor = $("#" + lDatagrid_ID).edatagrid('getEditor', {index:Arg_Index, field:field.Size_Postion});
												$(editor.target).numberbox({editable:true,}).textbox('addClearBtn', 'icon-clear');
											}
										})
									})
							    	//Datagrid_Editor_AddClearBtn(Arg_Datagrid, Arg_Index);
						    	} else if (data.Status == "fail") {
						    		//$(this).textbox("setValue", "")
						    		//alert(data.Result + "\n" + data.Cause)
						    		if (editor != null) {
					    				$(editor.target).textbox("setValue", "");
					    			}
						    	}
						    	
						    	//Payment_Amount
						    }
						})
						
					}
				}).textbox('addClearBtn', 'icon-clear');
			} else if (Valid_Size_Field(editor.field)) {
				$(editor.target).numberbox({
					onChange:function(newValue, oldValue) {
						alert("OK")
					}
				}).textbox('addClearBtn', 'icon-clear');
			}
		})
	}
}
/**
 * 检测是否是尺码字段
 * @param Arg_Field
 * @returns
 */
function Valid_Size_Field(Arg_Field) {
	var patrn=new RegExp("^S\\d+");///^S\\d+;//"^S\\d+";
	if (Arg_Field != undefined) {
		if (!Arg_Field.match(patrn)) return false
		return true
	} else {
		return false
	}	
}
/**
 * 图片压缩函数
 * @param file
 * @param maxLen
 * @param callBack
 * @returns
 */
function ImgToBase64(file, maxLen, callBack) {
	var img = new Image();

	var reader = new FileReader(); //读取客户端上的文件
	reader.readAsDataURL(file);
	reader.onload = function() {
		var url = this.result; //读取到的文件内容.这个属性只在读取操作完成之后才有效,并且数据的格式取决于读取操作是由哪个方法发起的.所以必须使用reader.onload，
		img.src = url; //reader读取的文件内容是base64,利用这个url就能实现上传前预览图片
	};
	img.onload = function() {
		//生成比例
		var width = img.width,
			height = img.height;
		//计算缩放比例
		var rate = 1;
		if(width >= height) {
			if(width > maxLen) {
				rate = maxLen / width;
			}
		} else {
			if(height > maxLen) {
				rate = maxLen / height;
			}
		};
		img.width = width * rate;
		img.height = height * rate;
		//生成canvas
		var canvas = document.createElement("canvas");
		var ctx = canvas.getContext("2d");
		canvas.width = img.width;
		canvas.height = img.height;
		ctx.drawImage(img, 0, 0, img.width, img.height);
		var base64 = canvas.toDataURL('image/jpeg', 0.9);
		callBack(base64);
	};
}
/**
 * 按照关键字读取cookie
 * @param name 关键字
 * @returns
 */
function getCookie(name){ 
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
 
    if(arr=document.cookie.match(reg))
 
        return unescape(arr[2]); 
    else 
        return null; 
} 
/**
 * 按照给定关键字写cookie
 * @param name 关键字
 * @param value cookie值
 * @returns
 */
function setCookie(name,value){ 
    var Days = 30; 
    var exp = new Date(); 
    exp.setTime(exp.getTime() + Days*24*60*60*1000); 
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); 
} 

/**
 * 按照关键字读取cookie
 * @param name 关键字
 * @returns
 */
function getSQL(Arg_Preset_SQL){ 
	var str = Arg_Preset_SQL; 
	str = str.match(/select(\s\S*)from/)[1]; 
	alert(str);//结果bbbcccdddeee
	var backgroundImageRegex=/select(\S*)from/;
	alert(Arg_Preset_SQL.match(/select(\S*)from/)[1]);
	var matchResult=Arg_Preset_SQL.match(backgroundImageRegex);
	if(matchResult.length>0){
	  alert(matchResult[0]);
	}
}
/**
 * 日期天数得到日期
 */
function dateChange(Arg_Days, Arg_BeginDate, Arg_FormatString){
	var date = Date.parse(new Date(Arg_BeginDate))/1000;//转换为时间戳
	date += 86400 * (Arg_Days - 1);
	var newDate = new Date(parseInt(date) * 1000);
	
	let ret;
    const opt = {
        "Y+": newDate.getFullYear().toString(),        // 年
        "m+": (newDate.getMonth() + 1).toString(),     // 月
        "d+": newDate.getDate().toString(),            // 日
        "H+": newDate.getHours().toString(),           // 时
        "M+": newDate.getMinutes().toString(),         // 分
        "S+": newDate.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(Arg_FormatString);
        if (ret) {
            Arg_FormatString = Arg_FormatString.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
	
	return Arg_FormatString;
}

/**
* 校验只要是数字（包含正负整数，0以及正负浮点数）就返回true
**/

function isNumber(val){

    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if(regPos.test(val) && regNeg.test(val)){
        return true;
    }else{
        return false;
    }

}
/**
 得到今天的日期
 */
function getToday(){
	var myDate = new Date;
    var year = myDate.getFullYear(); //获取当前年
    var mon = myDate.getMonth() + 1 < 10 ? '0' + (myDate.getMonth() + 1) : myDate.getMonth() + 1; //获取当前月
    var date = myDate.getDate() < 10 ? '0' + myDate.getDate() : myDate.getDate(); //获取当前日
    // var h = myDate.getHours();//获取当前小时数(0-23)
    // var m = myDate.getMinutes();//获取当前分钟数(0-59)
    // var s = myDate.getSeconds();//获取当前秒
    var week = myDate.getDay();
    var weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    console.log(year, mon, date, weeks[week])
    return year + "-" + mon + "-" + date;
}

$.extend($.fn.validatebox.defaults.rules, {   
    phoneNum: { //验证手机号  
        validator: function(value, param){
			if (value.length!=11){
				return false;
			} else {
				return /^1[3-8]+\d{9}$/.test(value);
			}
        },   
        message: '请输入正确的手机号码。'  
    },
   
    telNum:{ //既验证手机号，又验证座机号
      validator: function(value, param){
          return /(^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$)|(^((\d3\d3)|(\d{3}\-))?(1[358]\d{9})$)/.test(value);
         },   
         message: '请输入正确的电话号码。'
    }  
});
/**
改变日期控件只显示月份
 */
function changeDateBox(Arg_ID){
	$('#'+Arg_ID).datebox({

       //显示日趋选择对象后再触发弹出月份层的事件，初始化时没有生成月份层

       onShowPanel: function () {

          //触发click事件弹出月份层

          span.trigger('click');

          if (!tds)

            //延时触发获取月份对象，因为上面的事件触发和对象生成有时间间隔

            setTimeout(function() {

                tds = p.find('div.calendar-menu-month-inner td');

                tds.click(function(e) {

                   //禁止冒泡执行easyui给月份绑定的事件

                   e.stopPropagation();

                   //得到年份

                   var year = /\d{4}/.exec(span.html())[0] ,

                   //月份

                   //之前是这样的month = parseInt($(this).attr('abbr'), 10) + 1;

                   month = parseInt($(this).attr('abbr'), 10);  

 

         //隐藏日期对象                     

         $('#'+Arg_ID).datebox('hidePanel')

           //设置日期的值

           .datebox('setValue', year + '-' + month);

                        });

                    }, 0);

            },

            //配置parser，返回选择的日期

            parser: function (s) {

                if (!s) return new Date();

                var arr = s.split('-');

                return new Date(parseInt(arr[0], 10), parseInt(arr[1], 10) - 1, 1);

            },

            //配置formatter，只返回年月 之前是这样的d.getFullYear() + '-' +(d.getMonth());

            formatter: function (d) {

                var currentMonth = (d.getMonth()+1);

                var currentMonthStr = currentMonth < 10 ? ('0' + currentMonth) : (currentMonth + '');

                return d.getFullYear() + '-' + currentMonthStr;

            }

        });

 

        //日期选择对象

        var p = $('#'+Arg_ID).datebox('panel'),

        //日期选择对象中月份

        tds = false,

        //显示月份层的触发控件

        span = p.find('span.calendar-text');

        var curr_time = new Date();

 

        //设置前当月

        $("#"+Arg_ID).datebox("setValue", myformatter(curr_time));
}

//格式化日期

function myformatter(date) {

    //获取年份

    var y = date.getFullYear();

    //获取月份

    var m = date.getMonth() + 1;

    return y + '-' + m;

}

//格式化时间
function formatDate(dat){
    //获取年月日，时间
    var year = dat.getFullYear();
    var mon = (dat.getMonth()+1) < 10 ? "0"+(dat.getMonth()+1) : dat.getMonth()+1;
    var data = dat.getDate()  < 10 ? "0"+(dat.getDate()) : dat.getDate();
    var hour = dat.getHours()  < 10 ? "0"+(dat.getHours()) : dat.getHours();
    var min =  dat.getMinutes()  < 10 ? "0"+(dat.getMinutes()) : dat.getMinutes();
    var seon = dat.getSeconds() < 10 ? "0"+(dat.getSeconds()) : dat.getSeconds();
                 
    var newDate = year +"-"+ mon +"-"+ data;
    return newDate;
}
